package com.example.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.json.JSON.JSONArray;
import com.example.json.JSON.JSONObject;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;


@SuppressWarnings("serial")
public class StockServlet extends BaseServlet 
{
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException 
	{
		super.doGet(req, resp);
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = null;
		entities = Stock.getAllStocks();		
		out.println(Util.writeJSON(entities));
		
		/*
		JSONObject encoder = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		
		for (Entity entity : entities) 
		{
			jsonArray.put(entity);
		}
		
		encoder.put("Stocks", jsonArray);		
		out.println(encoder.toString());
		*/
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	{
		BufferedReader buff = req.getReader();
		char[] buf = new char[4 * 1024]; // 4 KB char buffer
		int len;
		
		BufferedReader reader = buff;
		
		while ((len = reader.read(buf, 0, buf.length)) != -1) 
		{
		}
		
		String json = new String(buf);
				
		JSONObject decoder = new JSONObject(new String(json));
		
		Double quantity = (Double)decoder.getDouble("quantity");
		String stockName = (String)decoder.getString("stock");
		String formula = (String)decoder.getString("formula");
		
		Stock.createStock(stockName, quantity, formula);
		
		resp.getWriter().println("OK");
	}
	
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	{
		BufferedReader buff = req.getReader();
		char[] buf = new char[4 * 1024]; // 4 KB char buffer
		int len;
		
		BufferedReader reader = buff;
		
		while ((len = reader.read(buf, 0, buf.length)) != -1) 
		{
		}
		
		String json = new String(buf);
				
		JSONObject decoder = new JSONObject(new String(json));
		
		Double quantity = (Double)decoder.getDouble("quantity");
		String stockName = (String)decoder.getString("stock");
		
		Stock.updateStock(stockName, quantity);
		
		resp.getWriter().println("OK");
	}
}
